package com.xmall.auth.xmallauth.jwt.filter;

import com.xmall.auth.service.XmallUserDetailsService;
import com.xmall.auth.xmallauth.jwt.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * BasicAuthenticationFilter   负责处理HTTPHeader中的基本认证信息。
 *
 * 工作原理：在header中获取特定key和特定形式的value（Authorization、Basic [Token]），
 * 获取的到，即使用当前过滤器进行验证身份信息。获取不到，则继续执行正常的过滤链。
 */
public class JWTAuthorizationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Autowired
    private XmallUserDetailsService xmallUserDetailsService;

  /*  public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
*/
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String header = request.getHeader(tokenHeader);
        // 如果请求头中没有Authorization信息则直接放行了
        if (header == null || !header.startsWith(tokenPrefix)) {
            chain.doFilter(request, response);
            return;
        }

        String token = header.replace(tokenPrefix, "");
        String username = jwtTokenUtil.getUserNameFromToken(token);
        UserDetails userDetails = xmallUserDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.validateToken(token, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
           // LOGGER.info("authenticated user:{}", username);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
       // super.doFilterInternal(request, response, chain);
        chain.doFilter(request, response);
    }


    @Bean
    public JwtTokenUtil jwtTokenUtil() {
        return new JwtTokenUtil();
    }
}
